package org.oschina.api.user.menu.service;

import java.util.ArrayList;
import java.util.List;
import org.oschina.Constants;
import org.oschina.Message;
import org.oschina.Module;
import org.oschina.ResultUtil;
import org.oschina.api.BaseService;
import org.oschina.bean.Result;
import org.oschina.security.annotation.Require;
import org.oschina.api.index.service.IndexService;
import org.oschina.api.user.menu.dao.UserMenuRoleDAO;
import org.oschina.api.user.menu.model.UserMenuRole;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class UserMenuRoleService extends BaseService {

	@Autowired
	private UserMenuRoleDAO menuRoleDAO;
	@Autowired
	private UserMenuService menuService;
	@Autowired
	private IndexService indexService;
	
	/**
	 * 更新
	 * @param role
	 * @param menuRoles
	 * @return
	 */
	@Require(authorization=Module.MODULE_45)
	public Result update(int role,int menuRoles[])
	{
		List<UserMenuRole> args=new ArrayList<UserMenuRole>();
		for(int menuRole:menuRoles)
		{
			if(menuService._findVoById(menuRole)==null)
				return ResultUtil.getFailure(Message.ERROR_DATA_ERROR);
			
			UserMenuRole temp=new UserMenuRole();
			temp.setId(_getIndex());
			temp.setMenu(menuRole);
			temp.setRole(role);
			args.add(temp);
		}
		menuRoleDAO.update(role, args);
		
		return ResultUtil.getSuccess(Message.UPDATE_SUCCESS);
	}
	
	/**
	 * 根据menu删除
	 * @param menu
	 * @return
	 */
	public int _removeByMenu(int menu)
	{
		return menuRoleDAO.removeByMenu(menu);
	}
	
	private int _getIndex()
	{
		return indexService.getMajorById(Constants.INDEX_USER_MENU_ROLE);
	}
}